<template>
    <el-dialog
      v-model="visible"
      title="报名人员管理"
      width="70%"
      :before-close="handleClose"
      draggable
      destroy-on-close
    >
      <div v-if="task" class="applicants-dialog">
        <!-- 任务基本信息 -->
        <el-card shadow="never" class="task-info-card">
          <div class="task-header">
            <div class="task-basic">
              <h3>{{ task.taskName }}</h3>
              <el-tag :type="getStatusType(task.taskStatus)" size="large">
                {{ task.taskStatus }}
              </el-tag>
            </div>
            <div class="task-meta">
              <span class="meta-item">
                <el-icon><User /></el-icon>
                需要 {{ task.personnelCount }} 人
              </span>
              <span class="meta-item">
                <el-icon><Calendar /></el-icon>
                截止: {{ task.deadline }}
              </span>
            </div>
          </div>
        </el-card>
  
        <!-- 人员管理区域 -->
        <div class="personnel-management">
          <el-row :gutter="20">
            <!-- 报名人员列表 -->
            <el-col :xs="24" :md="12">
              <el-card shadow="never" class="personnel-card">
                <template #header>
                  <div class="card-header">
                    <span class="card-title">
                      <el-icon><UserFilled /></el-icon>
                      报名人员 ({{ task.applicants.length }})
                    </span>
                  </div>
                </template>
                
                <div class="personnel-list">
                  <div v-if="task.applicants.length === 0" class="empty-state">
                    <el-empty 
                      description="暂无报名人员" 
                      :image-size="80"
                    />
                    <div class="empty-tip">
                      没有报名人员时，可直接在右侧设置承接人
                    </div>
                  </div>
                  
                  <div v-else class="applicant-list">
                    <div 
                      v-for="applicant in task.applicants" 
                      :key="applicant"
                      class="applicant-item"
                      :class="{ 'is-assigned': localAssignees.includes(applicant) }"
                    >
                      <div class="applicant-info">
                        <el-avatar :size="36">
                          {{ applicant.charAt(0) }}
                        </el-avatar>
                        <div class="applicant-details">
                          <div class="applicant-name">{{ applicant }}</div>
                          <div class="applicant-status">
                            <el-tag 
                              v-if="localAssignees.includes(applicant)" 
                              type="success" 
                              size="small"
                            >
                              已承接
                            </el-tag>
                            <el-tag v-else type="info" size="small">
                              报名中
                            </el-tag>
                          </div>
                        </div>
                      </div>
                      
                      <div class="applicant-actions">
                        <el-button
                          v-if="!localAssignees.includes(applicant)"
                          type="primary"
                          size="small"
                          @click="assignTask(applicant)"
                          :disabled="localAssignees.length >= task.personnelCount"
                        >
                          设为承接人
                        </el-button>
                        <el-button
                          v-else
                          type="warning"
                          size="small"
                          @click="unassignTask(applicant)"
                        >
                          取消承接
                        </el-button>
                      </div>
                    </div>
                  </div>
                </div>
              </el-card>
            </el-col>
            
            <!-- 承接人员列表 -->
            <el-col :xs="24" :md="12">
              <el-card shadow="never" class="personnel-card">
                <template #header>
                  <div class="card-header">
                    <span class="card-title">
                      <el-icon><Avatar /></el-icon>
                      承接人员 ({{ localAssignees.length }}/{{ task.personnelCount }})
                    </span>
                    <el-progress 
                      :percentage="Math.round((localAssignees.length / task.personnelCount) * 100)"
                      :color="getProgressColor(localAssignees.length, task.personnelCount)"
                      :stroke-width="6"
                      style="width: 120px;"
                    />
                  </div>
                </template>
                
                <!-- 手动添加承接人 -->
                <div class="manual-assign" v-if="localAssignees.length < task.personnelCount">
                  <div class="add-assignee-form">
                    <el-select
                      v-model="selectedPerson"
                      placeholder="选择或输入人员姓名"
                      filterable
                      allow-create
                      style="width: 200px; margin-right: 8px;"
                      :disabled="localAssignees.length >= task.personnelCount"
                    >
                      <!-- 如果有报名人员，优先显示未承接的报名人员 -->
                      <el-option
                        v-for="person in availablePersons"
                        :key="person"
                        :label="person"
                        :value="person"
                      />
                      <!-- 预设的人员选项（可以从接口获取） -->
                      <el-option
                        v-for="person in systemUsers.filter(user => !localAssignees.includes(user) && !task.applicants.includes(user))"
                        :key="person"
                        :label="person"
                        :value="person"
                      />
                    </el-select>
                    <el-button
                      type="primary"
                      size="default"
                      @click="addManualAssignee"
                      :disabled="!selectedPerson || localAssignees.includes(selectedPerson) || localAssignees.length >= task.personnelCount"
                    >
                      <el-icon><Plus /></el-icon>
                      添加承接人
                    </el-button>
                  </div>
                  <div class="add-tips">
                    <el-text size="small" type="info">
                      {{ task.applicants.length > 0 ? '可从报名人员中选择，也可手动添加其他人员' : '请选择或输入承接人员姓名' }}
                    </el-text>
                  </div>
                </div>
                
                <div class="personnel-list">
                  <div v-if="localAssignees.length === 0" class="empty-state">
                    <el-empty 
                      description="暂无承接人员" 
                      :image-size="80"
                    />
                  </div>
                  
                  <div v-else class="assignee-list">
                    <div 
                      v-for="(assignee, index) in localAssignees" 
                      :key="assignee"
                      class="assignee-item"
                    >
                      <div class="assignee-info">
                        <el-avatar :size="36">
                          {{ assignee.charAt(0) }}
                        </el-avatar>
                        <div class="assignee-details">
                          <div class="assignee-name">{{ assignee }}</div>
                          <div class="assignee-meta">
                            <el-tag type="success" size="small">
                              承接人 #{{ index + 1 }}
                            </el-tag>
                            <!-- 显示人员来源 -->
                            <el-tag 
                              v-if="task.applicants.includes(assignee)" 
                              type="primary" 
                              size="small"
                              style="margin-left: 4px;"
                            >
                              报名人员
                            </el-tag>
                            <el-tag 
                              v-else 
                              type="warning" 
                              size="small"
                              style="margin-left: 4px;"
                            >
                              手动添加
                            </el-tag>
                          </div>
                        </div>
                      </div>
                      
                      <div class="assignee-actions">
                        <el-button
                          type="danger"
                          size="small"
                          text
                          @click="unassignTask(assignee)"
                        >
                          移除
                        </el-button>
                      </div>
                    </div>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
  
        <!-- 批量操作 -->
        <el-card shadow="never" class="batch-operations" v-if="task.applicants.length > 0 || localAssignees.length > 0">
          <template #header>
            <div class="card-header">
              <span class="card-title">
                <el-icon><Operation /></el-icon>
                批量操作
              </span>
            </div>
          </template>
          
          <div class="batch-actions">
            <el-button
              v-if="task.applicants.length > 0"
              type="primary"
              @click="batchAssign"
              :disabled="localAssignees.length >= task.personnelCount || unassignedApplicants.length === 0"
            >
              <el-icon><Plus /></el-icon>
              批量设为承接人
            </el-button>
            
            <el-button
              type="warning"
              @click="clearAllAssignees"
              :disabled="localAssignees.length === 0"
            >
              <el-icon><Minus /></el-icon>
              清空所有承接人
            </el-button>
            
            <el-button
              v-if="task.applicants.length > 0"
              type="success"
              @click="autoAssign"
              :disabled="localAssignees.length >= task.personnelCount || task.applicants.length === 0"
            >
              智能分配
            </el-button>
          </div>
          
          <div class="batch-info">
            <el-alert
              v-if="localAssignees.length > task.personnelCount"
              title="承接人数超出需求"
              type="warning"
              :description="`当前承接人数 ${localAssignees.length} 超出需求人数 ${task.personnelCount}`"
              show-icon
              :closable="false"
            />
            <el-alert
              v-else-if="localAssignees.length === task.personnelCount"
              title="人员分配完成"
              type="success"
              description="承接人数已满足任务需求"
              show-icon
              :closable="false"
            />
            <el-alert
              v-else-if="localAssignees.length > 0"
              title="人员分配进行中"
              type="info"
              :description="`还需要 ${task.personnelCount - localAssignees.length} 人`"
              show-icon
              :closable="false"
            />
          </div>
        </el-card>
  
        <!-- 变更记录 -->
        <el-card shadow="never" class="change-log" v-if="changeLog.length > 0">
          <template #header>
            <div class="card-header">
              <span class="card-title">
                <el-icon><Document /></el-icon>
                本次变更记录
              </span>
            </div>
          </template>
          
          <el-timeline class="change-timeline">
            <el-timeline-item
              v-for="(log, index) in changeLog"
              :key="index"
              :timestamp="log.time"
              :color="log.type === 'assign' ? '#67c23a' : '#e6a23c'"
            >
              <div class="change-content">
                <span>{{ log.action }}</span>
                <el-tag :type="log.type === 'assign' ? 'success' : 'warning'" size="small">
                  {{ log.person }}
                </el-tag>
              </div>
            </el-timeline-item>
          </el-timeline>
        </el-card>
      </div>
  
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button 
            type="primary" 
            @click="handleSave"
            :disabled="!hasChanges"
            :loading="saving"
          >
            保存更改
          </el-button>
        </div>
      </template>
    </el-dialog>
  </template>
  
  <script setup lang="ts">
  import { computed, ref, watch } from 'vue';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import {
    User,
    Calendar,
    UserFilled,
    Avatar,
    Operation,
    Plus,
    Minus,
    Document
  } from '@element-plus/icons-vue';
  
  interface TaskInfo {
    id: number;
    initiator: string;
    taskLevel: string;
    taskName: string;
    positionRequirement: string;
    taskContent: string;
    personnelCount: number;
    applicants: string[];
    assignees: string[];
    workHours: {
      startDate: string;
      endDate: string;
    };
    deadline: string;
    taskStatus: string;
    attachments: string[] | null;
    createdAt?: string;
    updatedAt?: string;
  }
  
  interface ChangeLogItem {
    time: string;
    action: string;
    person: string;
    type: 'assign' | 'unassign';
  }
  
  interface Props {
    visible: boolean;
    task: TaskInfo | null;
  }
  
  interface Emits {
    (e: 'update:visible', value: boolean): void;
    (e: 'refresh'): void;
  }
  
  const props = defineProps<Props>();
  const emit = defineEmits<Emits>();
  
  const visible = computed({
    get: () => props.visible,
    set: (value) => emit('update:visible', value)
  });
  
  // 本地状态
  const localAssignees = ref<string[]>([]);
  const originalAssignees = ref<string[]>([]);
  const saving = ref(false);
  const changeLog = ref<ChangeLogItem[]>([]);
  const selectedPerson = ref('');
  
  // 系统用户列表（可以从接口获取）
  const systemUsers = ref<string[]>([
    '张三', '李四', '王五', '赵六', '孙七', '周八', '吴九', '郑十',
    '刘一', '陈二', '杨三', '黄四', '朱五', '徐六', '何七', '马八'
  ]);
  
  // 计算属性
  const hasChanges = computed(() => {
    return JSON.stringify(localAssignees.value.sort()) !== JSON.stringify(originalAssignees.value.sort());
  });
  
  const unassignedApplicants = computed(() => {
    if (!props.task) return [];
    return props.task.applicants.filter(applicant => !localAssignees.value.includes(applicant));
  });
  
  // 可用人员列表（报名人员中未承接的）
  const availablePersons = computed(() => {
    if (!props.task) return [];
    return props.task.applicants.filter(person => !localAssignees.value.includes(person));
  });
  
  // 监听任务变化，初始化本地状态
  watch(() => props.task, (newTask) => {
    if (newTask) {
      localAssignees.value = [...(newTask.assignees || [])];
      originalAssignees.value = [...(newTask.assignees || [])];
      changeLog.value = [];
      selectedPerson.value = '';
    }
  }, { immediate: true });
  
  // 方法
  const handleClose = () => {
    if (hasChanges.value) {
      ElMessageBox.confirm(
        '有未保存的更改，确定要关闭吗？',
        '确认关闭',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(() => {
        resetChanges();
        visible.value = false;
      }).catch(() => {
        // 用户取消，不关闭对话框
      });
    } else {
      visible.value = false;
    }
  };
  
  const handleSave = async () => {
    if (!props.task) return;
    
    saving.value = true;
    
    try {
      // 模拟保存操作
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      // 这里应该调用API保存数据
      // await saveTaskAssignees(props.task.id, localAssignees.value);
      
      ElMessage.success('保存成功');
      emit('refresh');
      visible.value = false;
    } catch (error) {
      ElMessage.error('保存失败');
    } finally {
      saving.value = false;
    }
  };
  
  const assignTask = (person: string) => {
    if (!props.task) return;
    
    if (localAssignees.value.length >= props.task.personnelCount) {
      ElMessage.warning('承接人数已达上限');
      return;
    }
    
    if (!localAssignees.value.includes(person)) {
      localAssignees.value.push(person);
      addChangeLog('设为承接人', person, 'assign');
      ElMessage.success(`已将 ${person} 设为承接人`);
    }
  };
  
  const unassignTask = (person: string) => {
    const index = localAssignees.value.indexOf(person);
    if (index > -1) {
      localAssignees.value.splice(index, 1);
      addChangeLog('取消承接', person, 'unassign');
      ElMessage.success(`已取消 ${person} 的承接`);
    }
  };
  
  // 新增：手动添加承接人
  const addManualAssignee = () => {
    if (!props.task || !selectedPerson.value) return;
    
    if (localAssignees.value.length >= props.task.personnelCount) {
      ElMessage.warning('承接人数已达上限');
      return;
    }
    
    if (localAssignees.value.includes(selectedPerson.value)) {
      ElMessage.warning('该人员已是承接人');
      return;
    }
    
    localAssignees.value.push(selectedPerson.value);
    const actionText = props.task.applicants.includes(selectedPerson.value) ? '从报名人员中设为承接人' : '手动添加承接人';
    addChangeLog(actionText, selectedPerson.value, 'assign');
    ElMessage.success(`已将 ${selectedPerson.value} 设为承接人`);
    selectedPerson.value = '';
  };
  
  const batchAssign = () => {
    if (!props.task) return;
    
    const availableSlots = props.task.personnelCount - localAssignees.value.length;
    const toAssign = unassignedApplicants.value.slice(0, availableSlots);
    
    toAssign.forEach(person => {
      localAssignees.value.push(person);
      addChangeLog('批量设为承接人', person, 'assign');
    });
    
    ElMessage.success(`已批量设置 ${toAssign.length} 人为承接人`);
  };
  
  const clearAllAssignees = () => {
    ElMessageBox.confirm(
      '确定要清空所有承接人吗？',
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(() => {
      const cleared = [...localAssignees.value];
      localAssignees.value = [];
      cleared.forEach(person => {
        addChangeLog('批量取消承接', person, 'unassign');
      });
      ElMessage.success('已清空所有承接人');
    });
  };
  
  const autoAssign = () => {
    if (!props.task) return;
    
    const availableSlots = props.task.personnelCount - localAssignees.value.length;
    const toAssign = unassignedApplicants.value.slice(0, availableSlots);
    
    toAssign.forEach(person => {
      localAssignees.value.push(person);
      addChangeLog('智能分配', person, 'assign');
    });
    
    ElMessage.success(`智能分配完成，已设置 ${toAssign.length} 人为承接人`);
  };
  
  const resetChanges = () => {
    if (props.task) {
      localAssignees.value = [...(props.task.assignees || [])];
      changeLog.value = [];
      selectedPerson.value = '';
    }
  };
  
  const addChangeLog = (action: string, person: string, type: 'assign' | 'unassign') => {
    changeLog.value.unshift({
      time: new Date().toLocaleTimeString(),
      action,
      person,
      type
    });
  };
  
  const getStatusType = (status: string) => {
    const statusMap: Record<string, string> = {
      '已承接': 'success',
      '未承接': 'warning',
      '任务结束': 'info'
    };
    return statusMap[status] || 'info';
  };
  
  const getProgressColor = (current: number, total: number) => {
    const percentage = (current / total) * 100;
    if (percentage === 100) return '#67c23a';
    if (percentage >= 50) return '#e6a23c';
    return '#409eff';
  };
  </script>
  
  <style lang="scss" scoped>
  .applicants-dialog {
    .task-info-card {
      margin-bottom: 20px;
      
      .task-header {
        .task-basic {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 12px;
          
          h3 {
            margin: 0;
            color: #000;
            font-size: 18px;
          }
        }
        
        .task-meta {
          display: flex;
          gap: 20px;
          
          .meta-item {
            display: flex;
            align-items: center;
            font-size: 14px;
            color: #606266;
            
            .el-icon {
              margin-right: 6px;
            }
          }
        }
      }
    }
    
    .personnel-management {
      margin-bottom: 20px;
      
      .personnel-card {
        min-height: 500px;
        
        .card-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          
          .card-title {
            display: flex;
            align-items: center;
            font-size: 16px;
            font-weight: 600;
            color: #000;
            
            .el-icon {
              margin-right: 8px;
            }
          }
        }
        
        .manual-assign {
          margin-bottom: 16px;
          padding-bottom: 16px;
          border-bottom: 1px solid #f0f0f0;
          
          .add-assignee-form {
            display: flex;
            align-items: center;
            margin-bottom: 8px;
          }
          
          .add-tips {
            font-size: 12px;
            color: #909399;
          }
        }
        
        .personnel-list {
          max-height: 400px;
          overflow-y: auto;
          
          .empty-state {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 200px;
            
            .empty-tip {
              margin-top: 10px;
              font-size: 14px;
              color: #909399;
            }
          }
          
          .applicant-item, .assignee-item {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 16px;
            margin-bottom: 12px;
            background: #f8f9fa;
            border-radius: 8px;
            border-left: 4px solid transparent;
            transition: all 0.3s;
            
            &:hover {
              background: #f0f2f5;
            }
            
            &.is-assigned {
              border-left-color: #67c23a;
              background: #f0f9ff;
            }
            
            .applicant-info, .assignee-info {
              display: flex;
              align-items: center;
              flex: 1;
              
              .applicant-details, .assignee-details {
                margin-left: 12px;
                
                .applicant-name, .assignee-name {
                  font-size: 14px;
                  font-weight: 500;
                  color: #000;
                  margin-bottom: 4px;
                }
                
                .applicant-status, .assignee-meta {
                  font-size: 12px;
                  display: flex;
                  align-items: center;
                  flex-wrap: wrap;
                  gap: 4px;
                }
              }
            }
            
            .applicant-actions, .assignee-actions {
              display: flex;
              gap: 8px;
            }
          }
          
          .assignee-item {
            border-left-color: #67c23a;
            background: #f0f9ff;
          }
        }
      }
    }
    
    .batch-operations {
      margin-bottom: 20px;
      
      .batch-actions {
        display: flex;
        gap: 12px;
        margin-bottom: 16px;
        flex-wrap: wrap;
      }
      
      .batch-info {
        .el-alert {
          margin-bottom: 12px;
          
          &:last-child {
            margin-bottom: 0;
          }
        }
      }
    }
    
    .change-log {
      .change-timeline {
        max-height: 200px;
        overflow-y: auto;
        
        .change-content {
          display: flex;
          align-items: center;
          gap: 8px;
          font-size: 14px;
        }
      }
    }
  }
  
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
  }
  
  // 响应式样式
  @media (max-width: 768px) {
    .applicants-dialog {
      .personnel-management {
        .personnel-card {
          margin-bottom: 16px;
          
          .manual-assign {
            .add-assignee-form {
              flex-direction: column;
              align-items: stretch;
              gap: 8px;
              
              .el-select {
                width: 100% !important;
                margin-right: 0 !important;
              }
            }
          }
          
          .personnel-list {
            max-height: 300px;
          }
        }
      }
      
      .batch-actions {
        flex-direction: column;
      }
    }
  }
  </style>
  
  <style lang="scss">
  .applicants-dialog {
    .el-card__body {
      padding: 16px;
    }
    
    .personnel-list {
      scrollbar-width: thin;
      scrollbar-color: #ddd transparent;
      
      &::-webkit-scrollbar {
        width: 6px;
      }
      
      &::-webkit-scrollbar-thumb {
        background: #ddd;
        border-radius: 3px;
      }
    }
  }
  </style>